package cn.com.fattiger.framework.cms.admin.common.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.fattiger.framework.cms.admin.common.model.Menu;
import cn.com.fattiger.framework.cms.admin.common.model.User;
import cn.com.fattiger.framework.cms.admin.common.model.UserAttribute;
import cn.com.fattiger.framework.cms.admin.common.service.MenuService;
import cn.com.fattiger.framework.cms.admin.common.service.UserService;
import cn.com.fattiger.framework.cms.util.MD5;
import cn.com.fattiger.framework.cms.util.MenuUtil;
import cn.com.fattiger.framework.cms.util.StringUtil;

/**
 * Created by Administrator on 2015/11/27.
 */
@Controller
@RequestMapping(name = "admin")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    MenuService menuService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping(value = "login.do")
    public String login(String name, String pass, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
        try {

            if (StringUtil.isEmpty(name) || StringUtil.isEmpty(pass)) {
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("userName")) {
                        map.put("userName", cookie.getValue());
                    } else if (cookie.getName().equals("userPass")) {
                        map.put("userPass", cookie.getValue());
                    }
                }
                return "login";
            }

            String _pass = MD5.get(pass);

            List<User> users = userService.login(name, _pass);//findOne
            if (users.size() > 0) {

                Cookie cookie_name = new Cookie("userName", name);
                cookie_name.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(cookie_name);
                Cookie cookie_pass = new Cookie("userPass", pass);
                cookie_pass.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(cookie_pass);

                User _user = users.get(0);
                if (_user.getMenu().size() == 0 && _user.getType() == -1) {
                    List<Menu> menus = menuService.queryMenus();
                    _user.setMenu(menus);
                }

                List<String> permissions = new ArrayList<String>();
                for (Menu menu : _user.getMenu()) {
                    String url = menu.getJurl();
                    if (null != url && url.trim().length() > 0) {
                        permissions.add(url);
                    }
                }
                request.getSession().setAttribute("__PERMISSION__", permissions);
                request.getSession().setAttribute("__USER__", _user);
                response.sendRedirect("frameCtl.do");
                return "";
            } else {
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("userName")) {
                        map.put("userName", cookie.getValue());
                    } else if (cookie.getName().equals("userPass")) {
                        map.put("userPass", cookie.getValue());
                    }
                }
                map.put("error", "user or pass invalid!");
                return "login";
            }
        } catch (Exception e) {
            //e.printStackTrace();
            Cookie[] cookies = request.getCookies();
            if(null!=cookies) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("userName")) {
                        map.put("userName", cookie.getValue());
                    } else if (cookie.getName().equals("userPass")) {
                        map.put("userPass", cookie.getValue());
                    }
                }
            }
            map.put("error", e.getMessage());
            return "login";
        }
    }

    @RequestMapping(value = "logout.do")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("__USER__");
        request.getSession().removeAttribute("__PERMISSION__");
        return "login";
    }

    @RequestMapping(value = "saveUser.do", method = RequestMethod.POST)
    public String saveUser(User user, ModelMap map) {
        System.out.println("user:" + user);

        if (null != user.getPass()) {
            user.setPass(MD5.get(user.getPass()));
        }
        List<Integer> ids = new ArrayList<Integer>();
        for (Menu menu : user.getMenu()) {
            if (null != menu.getId()) {
                ids.add(menu.getId());
            }
        }

        List<Menu> menus = new ArrayList<Menu>();
        if (ids.size() > 0) {
            menus = menuService.queryMenuByIdIn(ids);
        }
        List<UserAttribute> userAttribute = new ArrayList<UserAttribute>();
        user.setMenu(menus);
        user.setUserAttribute(userAttribute);

        userService.addUser(user);
        return userList(map);
    }

    @RequestMapping(value = "deleteUser.do", method = RequestMethod.GET)
    public String deleteUser(Integer id, ModelMap map) {
        userService.deleteUser(id);
        return userList(map);
    }

    @RequestMapping(value = "getUser.do", method = RequestMethod.GET)
    public String getUser(Integer id, ModelMap map) {
        User user = null;
        if (null != id) {
            user = userService.getUser(id);
        }

        List<Menu> menus = menuService.queryMenus();
        map.put("menus", MenuUtil.packMenu(menus));
        map.put("user", user);
        return "user_edit";
    }

    @RequestMapping(value = "userList.do")
    public String userList(ModelMap map) {
        List<User> users = userService.queryUsers();
        map.put("users", users);
        return "user_list";
    }
    
    @RequestMapping(value="viewUser.do", method = RequestMethod.GET)
    public String viewUser(Integer id, ModelMap map){
    	User user = null;
        if (null != id) {
            user = userService.getUser(id);
        }
        List<Menu> menus = menuService.queryMenus();
        map.put("menus", MenuUtil.packMenu(menus));
        map.put("user", user);
        return "user_view";
    }

}
